//
//  comleteRegistViewController.m
//  B项目
//
//  Created by lanou on 16/8/6.
//  Copyright © 2016年 Work. All rights reserved.
//

#import "comleteRegistViewController.h"
#import "PrefixHeader.pch"
#import <AVOSCloud/AVOSCloud.h>
#import "LoaginViewController.h"
#import "YGValidator.h"
#import <MediaPlayer/MediaPlayer.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD.h"
@interface comleteRegistViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UIImagePickerController *pickController;
@property(nonatomic,strong)UIImageView *imgView;
@property(nonatomic,strong)UITextField *registUserTF;
@property(nonatomic,strong)UITextField *passWordUserTF;
@property(nonatomic,strong)UITextField *rePassWordUserTF;
@property(nonatomic,strong)UIImage *currentImage;
@property(nonatomic,strong)MBProgressHUD *HUD;
@end

@implementation comleteRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"注册 - 验证手机 快速注册 - 完善资料";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    //pickController
    self.pickController = [[UIImagePickerController alloc]init];
    self.pickController.delegate = self;
    _pickController.allowsEditing = YES;


    [self creatControl];

}

//返回点击事件
- (void)leftItemAction
{
    [self.navigationController popViewControllerAnimated:YES];

}


- (void)creatControl
{

    //头像
    self.imgView = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth-80)/2, 40, 80, 80)];
    self.imgView.layer.cornerRadius = self.imgView.bounds.size.width/2;
    self.imgView.clipsToBounds = YES;
    _imgView.image = [UIImage imageNamed:@"comment_profile_default@2x.png"];

    _imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    tap.numberOfTapsRequired = 1;
    [self.view addSubview:_imgView];
    [_imgView addGestureRecognizer:tap];



    //昵称
    UIView *registuserView = [[UIView alloc]initWithFrame:CGRectMake(20, _imgView.endY + 20, kScreenWidth - 40, 60)];

    UIView *registLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 45, registuserView.ownWidth, 1)];
    registLineView.backgroundColor = [UIColor grayColor];
    UIImageView *registUserImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];

    registUserImg.image = [UIImage imageNamed:@"login_username_icon@2x.png"];

    self.registUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, registuserView.ownWidth -40, 30)];

    _registUserTF.tag = 10;
    _registUserTF.delegate = self;
    _registUserTF.placeholder = @"昵称";
    _registUserTF.font = [UIFont systemFontOfSize:14];
    [_registUserTF setBorderStyle:(UITextBorderStyleNone)];
    [registuserView addSubview:_registUserTF];
    [registuserView addSubview:registUserImg];
    [registuserView addSubview:registLineView];
    [self.view addSubview:registuserView];

    //密码
    UIView *passWordView = [[UIView alloc]initWithFrame:CGRectMake(20, registuserView.endY, kScreenWidth - 40, 60)];

    UIView *lineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, passWordView.ownWidth, 1)];
    lineViewP.backgroundColor = [UIColor grayColor];
    UIImageView *passWordImg = [[UIImageView alloc]initWithFrame:CGRectMake(0,10, 30, 30)];
    passWordImg.image = [UIImage imageNamed:@"login_password_icon@2x.png"];

    self.passWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, passWordView.ownWidth -40, 30)];
    _passWordUserTF.tag = 11; //tag 值
    _passWordUserTF.delegate = self;
    self.passWordUserTF.delegate = self;
    _passWordUserTF.placeholder = @"密码";
    _passWordUserTF.font = [UIFont systemFontOfSize:14];
    [_passWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    [passWordView addSubview:lineViewP];
    [passWordView addSubview:passWordImg];
    [passWordView addSubview:_passWordUserTF];
    [self.view addSubview:passWordView];

    //再次确认密码
    UIView *reNewPassView = [[UIView alloc]initWithFrame:CGRectMake(20, passWordView.endY, kScreenWidth - 40, 60)];
    UIImageView *reNewImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 30, 30)];
    reNewImg.image = [UIImage imageNamed:@"password.png"];

    self.
    rePassWordUserTF = [[UITextField alloc]initWithFrame:CGRectMake(40, 10, reNewPassView.ownWidth -40, 30)];
    _rePassWordUserTF.delegate = self;
    _rePassWordUserTF.placeholder = @"确认密码";
    _rePassWordUserTF.delegate = self;
    _rePassWordUserTF.tag = 12;
    _rePassWordUserTF.font = [UIFont systemFontOfSize:14];
    [_rePassWordUserTF setBorderStyle:(UITextBorderStyleNone)];

    UIView *renewlineViewP = [[UIView alloc]initWithFrame:CGRectMake(0, 45, reNewPassView.ownWidth, 1)];
    renewlineViewP.backgroundColor = [UIColor grayColor];

    [reNewPassView addSubview:reNewImg];
    [reNewPassView addSubview:_rePassWordUserTF

     ];
    [reNewPassView addSubview:renewlineViewP];
    [self.view addSubview:reNewPassView];

    //完成
    UIImageView *compeleteImg = [[UIImageView alloc]initWithFrame:CGRectMake(20, reNewPassView.endY + 30, kScreenWidth - 40, 30)];
    compeleteImg.userInteractionEnabled = YES;
    compeleteImg.image = [UIImage imageNamed:@"login_tip_button@2x.png"];
    UIButton *compeleteBT = [[UIButton alloc]initWithFrame:CGRectMake((compeleteImg.ownWidth -60)/2, 0, 60, 30)];
    [compeleteBT setTitle:@"完成" forState:(UIControlStateNormal)];
    [compeleteBT setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [compeleteBT addTarget:self action:@selector(loaginBTAction) forControlEvents:(UIControlEventTouchUpInside)];
    [compeleteImg addSubview:compeleteBT];
    [self.view addSubview:compeleteImg];


}


//头像的轻拍事件
- (void)tapAction
{

    UIAlertController *alerC = [UIAlertController alertControllerWithTitle:@"选择" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *photoAlerAction = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeSavedPhotosAlbum)]) {
            NSArray *array = [UIImagePickerController availableMediaTypesForSourceType:(UIImagePickerControllerSourceTypeSavedPhotosAlbum)];
            self.pickController.mediaTypes = array;
            [self presentViewController:_pickController animated:YES completion:nil];
        }
    }];

    UIAlertAction *cameraAlerAction = [UIAlertAction actionWithTitle:@"照相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypeCamera)]) {
            self.pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:_pickController animated:YES completion:nil];

        }else{
            NSLog(@"无法打开相机");
        }

    }];


    UIAlertAction *cancelAlerAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];

    [alerC addAction:photoAlerAction];
    [alerC addAction:cameraAlerAction];
    [alerC addAction:cancelAlerAction];
    [self presentViewController:alerC animated:YES completion:nil];

}



//选择图片后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{

    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType  isEqualToString: @"public.image"]) {

        UIImage *selectImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        self.currentImage = selectImage;
        self.imgView.image = selectImage;

        [picker dismissViewControllerAnimated:YES completion:nil];

        //



    }
    else if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        self.imgView.image = info[UIImagePickerControllerEditedImage];
        //压缩图片
        //        NSData *fileData = UIImageJPEGRepresentation(self.imgView.image, 1.0);
        //保存图片至相册
        UIImageWriteToSavedPhotosAlbum(self.imgView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

    }



}

//图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    if (error) {
        NSLog(@"照片保存错误");
    }else{
        NSLog(@"保存成功");
    }

}



//点击完成事件
- (void)loaginBTAction
{

    if ([_registUserTF.text isEqualToString:@""]||[_passWordUserTF.text isEqualToString:@""]||[_rePassWordUserTF.text isEqualToString:@""]) {
        [self showAlert:@"用户名、密码等不能为空"];

    }else{

        AVUser *user = [AVUser user];
        user.username = self.registUserTF.text;
        user.password = self.passWordUserTF.text;
        user.mobilePhoneNumber = self.phoneNumber;

        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_rePassWordUserTF.text isEqualToString:_passWordUserTF.text]) {
                [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        UIAlertController * alerC = [UIAlertController alertControllerWithTitle:@"恭喜" message:@"注册成功" preferredStyle:(UIAlertControllerStyleAlert)];
                        UIAlertAction *alerAction = [UIAlertAction actionWithTitle:@"是" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

                            //将图片转化成data类型
                            NSData *data = UIImagePNGRepresentation(self.currentImage);
                            //将图片放在沙盒中的documents文件中
                            NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
                            //文件管理器
                            NSFileManager *fileManager = [NSFileManager defaultManager];
                            //把图片转换的data对象拷贝到沙盒中，并保存为image.png
                            [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
                            NSString *imagePath = [DocumentsPath stringByAppendingString:@"/image.png"];

                            [fileManager createFileAtPath:imagePath contents:data attributes:nil];
                            AVFile *file = [AVFile fileWithName:@"image.png" contentsAtPath: imagePath];

                            LoaginViewController *loadVC = [[LoaginViewController alloc]init];

                            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

                                AVUser *user = [AVUser user];
                                user.username = self.registUserTF.text;
                                user.password  = self.passWordUserTF.text;

                                [user setObject:file forKey:@"imageFile"];

                                AVFile *file =  user[@"imageFile"];
                                NSLog(@"=====================================================================================%@", file.url);

                                //            [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                                //
                                //            }];

                            }];

                            [self.navigationController pushViewController:loadVC animated:YES];
                        }] ;

                        UIAlertAction *alerAction2 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

                        }] ;

                        [self presentViewController:alerC animated:YES completion:nil];
                        [alerC addAction:alerAction];
                        [alerC addAction:alerAction2];
                        // 注册成功
                    } else {
                        // 失败的原因可能有多种，常见的是用户名已经存在。
                        [self showAlert:@"用户名已经存在或手机号已经使用"];
                        NSLog(@"%@",error);
                        NSLog(@"注册失败");
                    }
                }];

            }else
            {

                [self showAlert:@"两次密码输入不一致"];

            }


        });

        self.HUD = [[MBProgressHUD alloc]init];
        [self.view addSubview:self.HUD];
        self.HUD.dimBackground = YES;

        _HUD.mode = MBProgressHUDModeIndeterminate;
        _HUD.opacity = 0.8;
        _HUD.color = [UIColor redColor];
        _HUD.color = [_HUD.color colorWithAlphaComponent:1];
        _HUD.labelFont = [UIFont systemFontOfSize:13];
        self.HUD.labelText = @"loading...";
        _HUD.minShowTime = 5;
        _HUD.cornerRadius = 20.0;
        _HUD.animationType = MBProgressHUDAnimationZoomIn;
        [_HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];

    }



}


//任务，测试进度显示
- (void)myProgressTask {
    // This just increases the progress indicator in a loop
    float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        _HUD.progress = progress;
        usleep(50000);
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    if (textField.tag == 11) {
        //密码格式 /** 判断密码，6-16位 */
        NSMutableString *currentPassWordStr = [NSMutableString stringWithString:_passWordUserTF.text];
        [currentPassWordStr replaceCharactersInRange:range withString:string];
        [YGValidator validateText:currentPassWordStr regular:@"\\w{6,16}" textField:_passWordUserTF correctImage:@"true" errorImage:@"error"];
    }
    return YES;
}

//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSInteger tag = textField.tag;
    if (tag != 12) {
        [[self.view viewWithTag:tag + 1]becomeFirstResponder];
        
    }else{
        [[self.view viewWithTag:tag]resignFirstResponder];
    }
    
    return YES;
}


//点击事件的提示框

- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}


- (void)showAlert:(NSString *) _message{//时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
